<?php
	class Server {
		private $sock, $read, $clients;
		private $Config, $DB;
		
		function __construct() {
			global $Config;
			$this -> Config = $Config;
			$this -> DB = new Database();
			
			$this -> sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
			socket_bind($this -> sock, SERVER_HOST, SERVER_PORT) or die('Could not bind to port.');
			socket_listen($this -> sock);
			$this -> clients = array();
			$this -> read[0] = $this -> sock;
			
			$this -> listen();
			
			socket_close($this -> sock);
		}
		
		private function disconnect($index) {
			socket_close($this -> clients[$index]['sock']);
			unset($this -> clients[$index]);
			echo 'Client disconnected.', "\n";
		}
		
		private function handleRequest($data, $k) {
			$timestamp = unpack('L', $data);
			$timestamp = $timestamp[1];
			
			$sql = $this -> DB -> select(array('Severity'), 'Events', "`Timestamp` >= $timestamp", false, 'Severity', 'ASC');
			$row = $this -> DB -> row($sql);
			
			$response = 0;
			
			if (is_array($row)) {
				$response = (int) $row['Severity'];
			}
			
			$this -> respond($response, $k);
			
		}
		
		private function listen() {
			echo "Server established and listening on port ", SERVER_PORT, ".\n";
			while (true) {
				foreach ($this -> clients as $k => $client) {
					if ($client['sock'] !== NULL) {
						$this -> read[$k + 1] = $client['sock'];
					}
				}
				
				$ready = socket_select($this -> read, $a = NULL, $b = NULL, $c = NULL);
				
				if (in_array($this -> sock, $this -> read)) {
					$this -> clients[]['sock'] = socket_accept($this -> sock);
					echo 'Accepted client connection.', "\n";
				}
				
				foreach ($this -> clients as $k => $client) {
					$data = socket_read($client['sock'], SERVER_MSG_SIZE, PHP_BINARY_READ);
					if ($data == NULL) {
						// Client has disconnected
						$this -> disconnect($k);
					}
					
					// Parse data and write back here
					$this -> handleRequest($data, $k);
					
					// Close the connection when data delivered
					$this -> disconnect($k);
				}
			}
		}
		
		private function respond($data, $k) {
			echo 'Responding.', "\n";
			$data = pack('C', $data);
			socket_write($this -> clients[$k]['sock'], $data);
		}
	}
?>